#include "Socket.hpp"
#include <memory>
#include "Comm.hpp"
#include <iostream>
#include "Log.hpp"
#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Calculate.hpp"

void Usage(const std::string &proc)
{
    std::cout << "格式：" << proc << " port" << std::endl;
}
std::string HandlerRequest(std::string& packages)
{
    std::string resp_package;
    while(true)
    {
        //1.拆出有效载荷
        std::string req_message = DeCode(packages);
        std::cout << "HandlerRequest::req_message:" << req_message << std::endl;
        if(req_message == "") break;  //拆不出有效载荷

        //2.反序列化有效载荷，并填充进request里
        Factory* factory = new Factory();
        std::shared_ptr<Request> req_ptr = factory->BulidRequest();
        if(!req_ptr->DeSerialize(req_message)) break; //有效载荷格式不对
        std::cout << "req_ptr" << req_ptr->Serialize() << std::endl;
        //3.已成功拿到请求的数据，处理数据
        std::shared_ptr<Response> resp_ptr = Calculate().Cal(req_ptr);
        std::cout << "resp_ptr " << resp_ptr->GetState() << std::endl;
        //4.发送的准备
        //4.1.序列化这个response
        std::string resp_message = resp_ptr->Serialize();
        //4.2 添加报头
        std::string signal_resp_package = EnCode(resp_message);
        resp_package += signal_resp_package;
    }
    return resp_package;
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[1]);
        return usage_err;
    }
    uint16_t serverport = std::stoi(argv[1]);

    std::unique_ptr<TcpServer> tsvr = std::make_unique<TcpServer>(serverport, HandlerRequest);
    tsvr->Start();
}